<?php
return function () {
    $this->set('pretty');

    $ret = [
        'error' => 0,
        'msg' => ''
    ];

    $username = $_POST['username'];
    $password = $_POST['password'];

    if (empty($username)) {
        $ret['error'] = 1;
        $ret['msg'] = '用户名不能为空！';
    }
    if (empty($password)) {
        $ret['error'] = 1;
        $ret['msg'] = '密码不能为空！';
    }
    if ($ret['error']) {
        $this->send($ret);
        return;
    }

    $password = md5($password);

    $sql = "SELECT * FROM user WHERE username='%s' AND password='%s'";
    $rs = $this->mysql->query($sql, $username, $password);
    if ($rs) {
        $user = $rs[0];
        $_SESSION['user'] = TRUE;
        $_SESSION['user_id'] = $user->id;
        if ($user->is_admin)
            $_SESSION['is_admin'] = TRUE;
        else
            $_SESSION['is_admin'] = FALSE;
        
        $ret['msg'] = '登录成功。';
    } else {
        $ret['error'] = 1;
        $ret['msg'] = '用户名或密码错误，登录失败！';
    }

    $this->send($ret);
};